package io.kiki.sba.registry.server.clientInterface.remoting;

import io.kiki.sba.registry.api.ChannelHandler;
import io.kiki.sba.registry.api.Client;
import io.kiki.sba.registry.api.exchange.DataExchanger;
import io.kiki.sba.registry.api.exchange.RequestException;
import io.kiki.sba.registry.api.exchange.message.Request;
import io.kiki.sba.registry.api.exchange.message.Response;
import io.kiki.sba.registry.common.model.store.Url;
import io.kiki.sba.registry.server.clientInterface.bootstrap.Config;
import io.kiki.sba.registry.server.shared.remoting.ClientSideExchanger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;


public class DataNodeExchanger extends ClientSideExchanger {

    private static final Logger logger = LoggerFactory.getLogger(DataNodeExchanger.class);

    @Autowired
    private Config config;

    public DataNodeExchanger() {
        super(DataExchanger.DATA_SERVER_TYPE);
    }


    @Override
    public Response request(Request request) throws RequestException {
        Url url = request.getRequestUrl();
        try {
            return super.request(request);
        } catch (RequestException e) {
            logger.error("Error when request DataNode! Request url={}, request={}", url, request.getRequestBody(), e);
            throw e;
        }
    }

    @Override
    public Client connectServer() {
        Set<String> ips = serverIpSet;
        int count = tryConnectAllServer(ips);
        if (count != ips.size()) {
            throw new RuntimeException("failed to connect all dataServers: " + ips);
        }
        return getClient();
    }

    @Override
    protected Collection<ChannelHandler> getClientHandlers() {
        return Collections.emptyList();
    }

    @Override
    public int getRpcTimeoutMillis() {
        return config.getDataNodeExchangeTimeoutMillis();
    }

    @Override
    public int getServerPort() {
        return config.getDataServerPort();
    }

    @Override
    public int getConnNum() {
        return config.getDataClientConnNum();
    }
}
